//
//  DHSearchView.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/2/4.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHSearchView.h"
#import "DHSearchColorCell.h"
#import "DHSearchSceneCell.h"
#import "DHSearchCategoryCell.h"
#import "DHSearchSizeCell.h"
#import "DHSearchProductCell.h"
#import "Color.h"

@interface DHSearchView()<UITableViewDelegate, UITableViewDataSource>{
    NSInteger numberOfRowsInSection;
    NSMutableArray *colorArr;
    NSMutableArray *scenarioArr;
    NSMutableArray *categoryArr;
    NSMutableArray *sizesArr;
    BOOL loadColorCell;
    BOOL loadSceneCell;
    BOOL loadCategoryCell;
    BOOL loadSizeCell;
    CGFloat productCellHeight;
}

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *dataArray;

@property (strong, nonatomic) NSString *scene_id;
@property (strong, nonatomic) NSString *color_name;
@property (strong, nonatomic) NSString *category_id;
@property (strong, nonatomic) NSString *sex;
@property (strong, nonatomic) NSString *size_name;
@property (assign, nonatomic) NSInteger pageIndex;

@end

@implementation DHSearchView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        if (!self.tableView){
            self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
            [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
            self.tableView.delegate = self;
            self.tableView.dataSource = self;
            [self.tableView registerClass:[DHSearchColorCell class] forCellReuseIdentifier:kDHSearchColorCell];
            [self.tableView registerClass:[DHSearchSceneCell class] forCellReuseIdentifier:kDHSearchSceneCell];
            [self.tableView registerClass:[DHSearchCategoryCell class] forCellReuseIdentifier:kDHSearchCategoryCell];
            [self.tableView registerClass:[DHSearchSizeCell class] forCellReuseIdentifier:kDHSearchSizeCell];
            [self.tableView registerClass:[DHSearchProductCell class] forCellReuseIdentifier:kDHSearchProductCell];
            self.tableView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductsData)];
            [self addSubview:self.tableView];
        }
        numberOfRowsInSection = 4;
    }
    return self;
}

- (void)loadConditionData{
    [self loadColorData];
    [self loadSceneData];
    [self loadCategoryData];
    [self loadProductsData];
}

// 搜索颜色
- (void)loadColorData{
    [[DHNetAPIClient shareDHNetAPIClient] request_colorsAndBlock:^(id data, NSError *error) {
        [self.colorArr removeAllObjects];
        NSArray *tempArr = [data objectForKey:@"colors"];
        [tempArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            Color *color = [Color modelWithDictionary:obj];
            [self.colorArr addObject:color];
        }];
        loadColorCell = YES;
        [self.tableView reloadData];
    }];
}

// 搜索场景
- (void)loadSceneData{
    [[DHNetAPIClient shareDHNetAPIClient] request_scenesAndBlock:^(id data, NSError *error) {
        DHScenarioListModel *scenarioList = [DHScenarioListModel modelWithDictionary:data];
        [scenarioList updateScenarioTitleArr];
        [self.scenarioArr removeAllObjects];
        [self.scenarioArr addObjectsFromArray:scenarioList.scenes];
        loadSceneCell = YES;
        [self.tableView reloadData];
    }];
}

// 搜索类别
- (void)loadCategoryData{
    NSString *sex;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX]) {
        sex = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX];
    }
    if ([GlobalManager shareGlobalManager].user.sex) {
        sex = [GlobalManager shareGlobalManager].user.sex;
    }
    if (!sex) {
        sex = @"男";
    }
    [[DHNetAPIClient shareDHNetAPIClient] request_categoriesWithParams:@{@"sex":sex} andBlock:^(id data, NSError *error) {
        DHCategoryListModel *categoryList = [DHCategoryListModel modelWithDictionary:data];
        [self.categoryArr removeAllObjects];
        [self.categoryArr addObjectsFromArray:categoryList.categories];
        loadCategoryCell = YES;
        [self.tableView reloadData];
    }];
}

// 获取类别对应尺码
- (void)loadSizeWithCatrgoryID:(NSString *)category_id{
    [[DHNetAPIClient shareDHNetAPIClient] request_category_sizes_nameWithCategoryID:category_id andBlock:^(id data, NSError *error) {
        [self.sizesArr removeAllObjects];
        [self.sizesArr addObjectsFromArray:[data objectForKey:@"sizes"]];
        loadSizeCell = YES;
        [self.tableView reloadData];
    }];
}

// 获取产品
- (void)loadProductsData{
    self.pageIndex = 0;
    
//    self.isMoreData = YES;
//    self.isLoadMore = NO;
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:@(self.pageIndex) forKey:@"pageIndex"];
    [params setObject:@(20) forKey:@"pageSize"];
    if (self.scene_id) {
        [params setObject:self.scene_id forKey:@"scene_id"];
    }
    if (self.category_id) {
        [params setObject:self.category_id forKey:@"category_id"];
    }
    if (self.size_name) {
        [params setObject:self.size_name forKey:@"size_name"];
    }
    if (self.color_name) {
        [params setObject:self.color_name forKey:@"color_name"];
    }
    if ([GlobalManager shareGlobalManager].user.sex) {
        [params setObject:[GlobalManager shareGlobalManager].user.sex forKey:@"sex"];
    }
    
    [[DHNetAPIClient shareDHNetAPIClient] request_search_productsWithDictionary:params andBlock:^(id data, NSError *error) {
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:[data objectForKey:@"products"]];
        
        if (self.dataArray.count % 2 > 0) {
            productCellHeight = (self.dataArray.count / 2) * 317 + 317 + (self.pageIndex+1)*20;
        }else{
            productCellHeight = (self.dataArray.count / 2) * 317 + (self.pageIndex+1)*20;
        }
        
        if (self.dataArray.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        self.pageIndex += 1;
        [self.tableView reloadData];
    }];
}

// 获取更多产品
- (void)loadMoreProductsData{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:@(self.pageIndex) forKey:@"pageIndex"];
    [params setObject:@(20) forKey:@"pageSize"];
    if (self.scene_id) {
        [params setObject:self.scene_id forKey:@"scene_id"];
    }
    if (self.category_id) {
        [params setObject:self.category_id forKey:@"category_id"];
    }
    if (self.size_name) {
        [params setObject:self.size_name forKey:@"size_name"];
    }
    if (self.color_name) {
        [params setObject:self.color_name forKey:@"color_name"];
    }
    if ([GlobalManager shareGlobalManager].user.sex) {
        [params setObject:[GlobalManager shareGlobalManager].user.sex forKey:@"sex"];
    }
    
    [[DHNetAPIClient shareDHNetAPIClient] request_search_productsWithDictionary:params andBlock:^(id data, NSError *error) {
        NSArray *arr = [data objectForKey:@"products"];
        [self.dataArray addObjectsFromArray:arr];
        self.pageIndex += 1;
        if (self.dataArray.count % 2 > 0) {
            productCellHeight = (self.dataArray.count / 2) * 317 + 317 + (self.pageIndex+1)*20;
        }else{
            productCellHeight = (self.dataArray.count / 2) * 317 + (self.pageIndex+1)*20 ;
        }
        
        if (arr.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
    }];
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return numberOfRowsInSection;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (numberOfRowsInSection == 4) {
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2) {
            return 54;
        }else{
            return productCellHeight;
        }
    }else if (numberOfRowsInSection == 5){
        if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3) {
            return 54;
        }else{
            return productCellHeight;
        }
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DHSearchColorCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSearchColorCell forIndexPath:indexPath];
        [cell updateCellWithConditionArr:colorArr firstLoad:loadColorCell];
        loadColorCell = NO;
        return cell;
    }else if (indexPath.row == 1){
        DHSearchSceneCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSearchSceneCell forIndexPath:indexPath];
        [cell updateCellWithConditionArr:scenarioArr firstLoad:loadSceneCell];
        loadSceneCell = NO;
        return cell;
    }else if (indexPath.row == 2){
        DHSearchCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSearchCategoryCell forIndexPath:indexPath];
        [cell updateCellWithConditionArr:categoryArr firstLoad:loadCategoryCell];
        loadCategoryCell = NO;
        return cell;
    }else{
        if (numberOfRowsInSection == 4) {
            if (indexPath.row == 3) {
                DHSearchProductCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSearchProductCell forIndexPath:indexPath];
                [cell updateCellWithProductArr:self.dataArray andCollectionViewHeight:productCellHeight];
                return cell;
            }else{
                return nil;
            }
        }else{
            if (indexPath.row == 3) {
                DHSearchSizeCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSearchSizeCell forIndexPath:indexPath];
                [cell updateCellWithConditionArr:sizesArr firstLoad:loadSizeCell];
                loadSizeCell = NO;
                return cell;
            }else if (indexPath.row == 4){
                DHSearchProductCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHSearchProductCell forIndexPath:indexPath];
                [cell updateCellWithProductArr:self.dataArray andCollectionViewHeight:productCellHeight];
                return cell;
            }else{
                return nil;
            }
        }
    }
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:@"DHSearchColorCell"]) {
        if ([[userInfo objectForKey:@"color_name"] isKindOfClass:[NSNull class]]) {
            self.color_name = nil;
        }else{
            self.color_name = [userInfo objectForKey:@"color_name"];
        }
        [self loadProductsData];
    }else if ([eventName isEqualToString:@"DHSearchSceneCell"]){
        if ([[userInfo objectForKey:@"scene_id"] isKindOfClass:[NSNull class]]) {
            self.scene_id = nil;
        }else{
            self.scene_id = [userInfo objectForKey:@"scene_id"];
        }
        [self loadProductsData];
    }else if ([eventName isEqualToString:@"DHSearchCategoryCell"]){
        if ([[userInfo objectForKey:@"category_id"] isKindOfClass:[NSNull class]]) {
            self.category_id = nil;
            numberOfRowsInSection = 4;
            [self.tableView reloadData];
        }else{
            self.category_id = [userInfo objectForKey:@"category_id"];
            numberOfRowsInSection = 5;
            [self loadSizeWithCatrgoryID:self.category_id];
        }
        [self loadProductsData];
    }else if ([eventName isEqualToString:@"DHSearchSizeCell"]){
        if ([[userInfo objectForKey:@"size_name"] isKindOfClass:[NSNull class]]) {
            self.size_name = nil;
        }else{
            self.size_name = [userInfo objectForKey:@"size_name"];
        }
        [self loadProductsData];
    }
}

#pragma mark - GET AND SET
- (NSMutableArray *)colorArr{
    if (!colorArr) {
        colorArr = [NSMutableArray array];
    }
    return colorArr;
}

- (NSMutableArray *)scenarioArr{
    if (!scenarioArr) {
        scenarioArr = [NSMutableArray array];
    }
    return scenarioArr;
}

- (NSMutableArray *)categoryArr{
    if (!categoryArr) {
        categoryArr = [NSMutableArray array];
    }
    return categoryArr;
}

- (NSMutableArray *)sizesArr{
    if (!sizesArr) {
        sizesArr = [NSMutableArray array];
    }
    return sizesArr;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
